package controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StackServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/html");
		String content="";
		String link = request.getParameter("link");
		String charset="utf-8";
		URL url;
		try {
			Random random = new Random();
			List<String> listSock = new ArrayList<String>();
			listSock.add("184.107.74.40");
			listSock.add("184.107.74.41");
			listSock.add("184.107.74.42");
			listSock.add("184.107.74.43");
			listSock.add("184.107.74.44");
			listSock.add("184.107.74.45");
			listSock.add("184.107.74.46");
			listSock.add("184.107.74.47");
			int rand = new Random().nextInt(7);
			Socket sockket = new Socket(Utils.fomatDomain(link), 80, InetAddress.getByName(listSock.get(rand)), random.nextInt(1000)+30000);
//			Socket sockket = new Socket("www.alexa.com", 80);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sockket.getOutputStream()));
			
			writer.write("GET "+link+" HTTP/1.1\r\n");
			writer.write("Host: "+Utils.fomatDomain(link)+"\r\n");
			writer.write("Referer: http://5ty.org\r\n");
			
			writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
			writer.write("Connection:	Close\r\n");
			
			
			writer.write("\r\n\r\n");
			writer.flush();
			BufferedReader reader =  new BufferedReader(new InputStreamReader(sockket.getInputStream()));
			
			char[] buf = new char[102102];
			int numRead=0;
	        while((numRead=reader.read(buf)) != -1){
	            String readData = String.valueOf(buf, 0, numRead);
	            content += readData;
	            buf = new char[102102];
	        }
	        reader.close();
		}  catch (Exception e) {
			
			e.printStackTrace();
		}
		response.getWriter().println(content);
	}
}
